<?php
/*
 * @Author: lokei
 * @Date: 2023-05-12 17:31:09
 * @LastEditors: lokei
 * @LastEditTime: 2023-05-13 18:49:01
 * @Description: 
 */
namespace App\Http\Controllers\Pay\Exchange;

use App\Common\Tools\RandomTool;
use App\Common\Tools\ResultTool;
use App\Http\Controllers\Controller;
use App\Models\Member\LevelModel;
use App\Models\Pay\Exchange\CodeModel;
use Illuminate\Http\Request;

class CodeController extends Controller {
    public function list(Request $request) {
        if($request->input('name') != null && $request->input('name') != '') {
            $items = CodeModel::where('name', '=', $request->input('name'))->orderBy('created_at', 'desc')->get();
        } else {
            $items = CodeModel::orderBy('created_at', 'desc')->get();
        }
        $res = ResultTool::success();
        $res['data']['items'] = $items;
        $res['data']['total'] = count($items);
        return $res;
    }

    public function create(Request $request) {
        $amount = intval($request->input('amount'));
        if($amount > 0) {
            if($request->input('name') != null && $request->input('name') != '') {
                $name = $request->input('name');
            } else {
                $level = LevelModel::where('id', '=', $request->input('level_id'))->first();
                $name = $level->name . '兑换码';
            }
            for($i = 0; $i < $amount; $i++) {
                $code = new CodeModel();
                $code->code = RandomTool::GetRandStr(8);
                $code->name = $name;
                $code->status = '0';
                $code->created_at = date('Y-m-d H:i:s', time());
                $code->level_id = $request->input('level_id');
                $code->save();
            }
        }
        return ResultTool::success();
    }

    public function delete(Request $request) {
        CodeModel::where('id', '=', $request->input('id'))->delete();
        return ResultTool::success();
    }
}